package com.magist.manage.util;

import com.magist.core.auth.AuthUser;
import com.magist.core.entity.CxtHolder;
import com.magist.core.exception.BusinessException;
import com.magist.manage.web.entity.BusinessLog;
import com.magist.manage.web.service.BusinessLogService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Component
public class BusinessLogUtil {

    @Autowired
    private BusinessLogService businessLogService;

    Logger logger = LoggerFactory.getLogger(BusinessLogUtil.class);

    public void recordBusinessLog(String opAction, String optType, String businessId, String opTitle, String optContent) {

        try {
            if (StringUtils.isEmpty(optType) || StringUtils.isEmpty(optContent)) {
                throw new BusinessException("参数不能为空");
            }
            if (opTitle.endsWith(",")) {
                opTitle = opTitle.substring(0, opTitle.length() - 1);
            }
            if (optContent.endsWith(",")) {
                optContent = optContent.substring(0, optContent.length() - 1);
            }
            AuthUser user = CxtHolder.getUser();
            BusinessLog businessLog = new BusinessLog();

            if(!ObjectUtils.isEmpty(user)) {
                businessLog.setUserId(user.getUserId());
                businessLog.setUserName(user.getUserName());
            }
            businessLog.setOpTitle(opTitle);
            businessLog.setOpContent(optContent);
            businessLog.setBusinessId(businessId);
            businessLog.setOpAction(opAction);
            businessLog.setOpType(optType);
            businessLog.setOpTime(new Date());
            businessLog.setId(businessLogService.getNewId());
            businessLogService.insert(businessLog);
        } catch (Exception e) {
            logger.error("记录操作日志失败");
        }

    }
}
